package it.polimi.meteocal.ejb.notificationmanagement;


import java.util.ArrayList;
import java.util.List;

import it.polimi.meteocal.ejb.eventmanagement.Event;
import it.polimi.meteocal.ejb.invitationmanagement.Invitation;
import it.polimi.meteocal.ejb.usermanagement.User;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class NotificationMgrBean implements NotificationMgr {

	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;

	@Override
	public void save(NotificationDTO nuovo) {
		Notification notification = new Notification();
		notification.setText(nuovo.getText());
		notification.setType(nuovo.getType());
		notification.setUser(em.find(User.class,getPrincipalUser().getEmail()));
		em.persist(notification);
	}
	
	public User trova(String username){
		return em.find(User.class, username);
	}
	
	public User getPrincipalUser(){
		return trova(getPrincipalUsername());
	}
	
	public String getPrincipalUsername(){
		return context.getCallerPrincipal().getName();
	}

	@Override
	public List<?> findByUser() {
		Query q = em.createNamedQuery("Notification.findUserNotifications"); 
		q.setParameter("email", getPrincipalUser().getEmail());
		System.out.println("num: "+q.getResultList().size());
		return q.getResultList();
	}

	@Override
	public void delete(int notificationid) {
		/*Query q = em.createNamedQuery("Notification.deleteById"); 
		q.setParameter("notificationid", notificationid);
		System.out.println("num: "+q.getResultList().size());
		*/
		Notification notification = em.find(Notification.class, notificationid);
		//em.getTransaction().begin();
		em.remove(notification);
		//em.getTransaction().commit();
	}
	
	@Override
	public void notifyUsers(List<?> rawInvitations,String message){
		List<Invitation> invitations = new ArrayList<Invitation>();
		for(Object elem: rawInvitations){
    		invitations.add((Invitation) elem);
    	}
		for(int i=0;i<invitations.size();i++){
			User user = invitations.get(i).getUser();
			Notification newNotification = new Notification();
			newNotification.setText(message);
			newNotification.setType("m");
			newNotification.setUser(user);
			em.persist(newNotification);
		}
	}
	
}
